"""
真实交通数据API集成
支持高德地图、12306、飞常准等API
"""
import requests
import json
from datetime import datetime, timedelta

class RealTransportAPI:
    def __init__(self):
        # 从配置文件读取API密钥
        try:
            from api_keys import GAODE_API_KEY, FLIGHT_API_KEY, RAILWAY_API_CONFIG
            self.gaode_key = GAODE_API_KEY
            self.flight_key = FLIGHT_API_KEY
            self.railway_config = RAILWAY_API_CONFIG
        except ImportError:
            # 如果配置文件不存在，使用默认值
            self.gaode_key = "YOUR_GAODE_API_KEY"
            self.flight_key = "YOUR_FLIGHT_API_KEY"
            self.railway_config = {
                'base_url': 'https://kyfw.12306.cn/otn/leftTicket/query',
                'headers': {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                }
            }
        
        self.railway_base_url = self.railway_config['base_url']
    
    def get_high_speed_rail(self, origin, destination, date=None):
        """获取高铁信息"""
        if not date:
            date = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')
        
        try:
            # 使用12306 API
            params = {
                'leftTicketDTO.train_date': date,
                'leftTicketDTO.from_station': self.get_station_code(origin),
                'leftTicketDTO.to_station': self.get_station_code(destination),
                'purpose_codes': 'ADULT'
            }
            
            response = requests.get(self.railway_base_url, params=params)
            data = response.json()
            
            if data.get('status') and data.get('data'):
                return self.parse_railway_data(data['data'])
            else:
                return self.get_mock_railway_data(origin, destination)
                
        except Exception as e:
            print(f"获取高铁数据失败: {e}")
            return self.get_mock_railway_data(origin, destination)
    
    def get_flight_info(self, origin, destination, date=None):
        """获取飞机信息"""
        if not date:
            date = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')
        
        try:
            # 使用飞常准API
            url = "https://api.flightradar24.com/common/v1/search.json"
            params = {
                'query': f"{origin} to {destination}",
                'limit': 10
            }
            
            response = requests.get(url, params=params)
            data = response.json()
            
            if data.get('results'):
                return self.parse_flight_data(data['results'])
            else:
                return self.get_mock_flight_data(origin, destination)
                
        except Exception as e:
            print(f"获取飞机数据失败: {e}")
            return self.get_mock_flight_data(origin, destination)
    
    def get_bus_info(self, origin, destination, date=None):
        """获取汽车信息"""
        if not date:
            date = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')
        
        try:
            # 使用高德地图API
            url = "https://restapi.amap.com/v3/direction/transit/integrated"
            params = {
                'key': self.gaode_key,
                'origin': f"{origin}站",
                'destination': f"{destination}站",
                'city': origin,
                'extensions': 'all'
            }
            
            response = requests.get(url, params=params)
            data = response.json()
            
            if data.get('status') == '1' and data.get('route'):
                return self.parse_bus_data(data['route'])
            else:
                return self.get_mock_bus_data(origin, destination)
                
        except Exception as e:
            print(f"获取汽车数据失败: {e}")
            return self.get_mock_bus_data(origin, destination)
    
    def get_station_code(self, city):
        """获取城市车站代码"""
        station_codes = {
            '北京': 'BJP',
            '上海': 'SHH',
            '广州': 'GZQ',
            '深圳': 'SZN',
            '杭州': 'HZH',
            '南京': 'NJH',
            '武汉': 'WHN',
            '成都': 'CDW',
            '西安': 'XAY',
            '重庆': 'CQW'
        }
        return station_codes.get(city, 'BJP')
    
    def parse_railway_data(self, data):
        """解析铁路数据"""
        routes = []
        for item in data:
            if item.get('queryLeftNewDTO'):
                train = item['queryLeftNewDTO']
                routes.append({
                    'type': 'high_speed_rail',
                    'train_number': train.get('station_train_code', ''),
                    'departure_time': train.get('start_time', ''),
                    'arrival_time': train.get('arrive_time', ''),
                    'duration': train.get('lishi', ''),
                    'price': train.get('zy_price', 0),
                    'seats_available': train.get('zy_num', '无')
                })
        return routes
    
    def parse_flight_data(self, data):
        """解析飞机数据"""
        routes = []
        for flight in data[:5]:  # 取前5个结果
            routes.append({
                'type': 'flight',
                'flight_number': flight.get('flight_number', ''),
                'departure_time': flight.get('departure_time', ''),
                'arrival_time': flight.get('arrival_time', ''),
                'duration': flight.get('duration', ''),
                'price': flight.get('price', 0),
                'airline': flight.get('airline', '')
            })
        return routes
    
    def parse_bus_data(self, data):
        """解析汽车数据"""
        routes = []
        for route in data.get('transits', [])[:3]:  # 取前3个结果
            routes.append({
                'type': 'bus',
                'description': route.get('instruction', ''),
                'duration': route.get('duration', ''),
                'price': route.get('cost', 0),
                'transfers': route.get('transits', 0)
            })
        return routes
    
    def get_mock_railway_data(self, origin, destination):
        """模拟铁路数据"""
        return [{
            'type': 'high_speed_rail',
            'train_number': 'G1',
            'departure_time': '08:00',
            'arrival_time': '12:30',
            'duration': '4.5小时',
            'price': 553,
            'seats_available': '有票'
        }]
    
    def get_mock_flight_data(self, origin, destination):
        """模拟飞机数据"""
        return [{
            'type': 'flight',
            'flight_number': 'CA1234',
            'departure_time': '09:30',
            'arrival_time': '12:00',
            'duration': '2.5小时',
            'price': 800,
            'airline': '中国国航'
        }]
    
    def get_mock_bus_data(self, origin, destination):
        """模拟汽车数据"""
        return [{
            'type': 'bus',
            'description': f'从{origin}到{destination}的长途汽车',
            'duration': '8小时',
            'price': 200,
            'transfers': 0
        }]

# 使用示例
if __name__ == "__main__":
    api = RealTransportAPI()
    
    # 获取高铁信息
    railway = api.get_high_speed_rail('北京', '上海')
    print("高铁信息:", railway)
    
    # 获取飞机信息
    flight = api.get_flight_info('北京', '上海')
    print("飞机信息:", flight)
    
    # 获取汽车信息
    bus = api.get_bus_info('北京', '上海')
    print("汽车信息:", bus)